package com.niit.gams.controller;

import com.github.pagehelper.PageInfo;
import com.niit.gams.pojo.SysRole;
import com.niit.gams.pojo.SysUser;
import com.niit.gams.pojo.TreeNode;
import com.niit.gams.service.SysRoleService;
import org.apache.shiro.SecurityUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/roles")
public class SysRoleController {
  private SysRoleService sysRoleService;

  public SysRoleController(SysRoleService sysRoleService) {
    this.sysRoleService = sysRoleService;
  }

  @GetMapping
  public ResponseEntity<PageInfo<SysRole>> findRolesByPage(@RequestParam(defaultValue = "1") Integer curPage, @RequestParam(defaultValue = "2")Integer pageSize){
    PageInfo<SysRole> pageInfo = sysRoleService.findUsersByPage(curPage,pageSize);
    return ResponseEntity.ok(pageInfo);
  }

  @PostMapping
  public ResponseEntity<Boolean> addRole(SysRole role){
    boolean flag = sysRoleService.addRole(role);
    return ResponseEntity.ok(flag);
  }

  @DeleteMapping("/{rid}")
  public ResponseEntity<Boolean> delRole(@PathVariable("rid")Integer rid){
    boolean flag = sysRoleService.delRole(rid);
    return ResponseEntity.ok(flag);
  }

  @GetMapping("/all")
  public ResponseEntity<List<TreeNode>> getAll(){
    List<SysRole> roles = sysRoleService.findRoles();
    List<TreeNode> treeNodes = new ArrayList<>();
    for (SysRole role:roles) {
      TreeNode node = new TreeNode();
      node.setId(role.getId());
      node.setName(role.getName());
      node.setPId(0L);
      treeNodes.add(node);
    }
    return ResponseEntity.ok(treeNodes);
  }

  @GetMapping("/rids/{uid}")
  public ResponseEntity<List<Long>> getAllRids(@PathVariable("uid") Long uid){
    List<Long> rids = sysRoleService.findRids(uid);
    return ResponseEntity.ok(rids);
  }

  @PutMapping
  public ResponseEntity<Boolean> updateUserRoles(Long uid, @RequestParam("rids") List<Long> rids){
    boolean flag = sysRoleService.updateUserRoles(uid,rids);
    return ResponseEntity.ok(flag);
  }
}
